package ar.com.photo_admin.service

import java.util.logging.Logger;

import ar.com.photo_admin.domain.*;
import grails.converters.*;

class EventAlbumService {

	def eventService;
	
	def findAlbumById(def albumId){
		def album = EventAlbum.get(albumId);
		album = album.refresh();
		return album;
	}
	
	def deleteAlbum(albumId){
		EventAlbum album = findAlbumById(albumId);
		log.info "Borrando el album: "+album.id		
		
		def event = album.event
		event.removeFromAlbums(album)

		album = album.refresh();
		album.coverPhoto = null;		
				
		album.delete();
		
		/*
		try {
			if(!album.delete(flush: true))
				throw new RuntimeException("No se pudo borrar el album");
		}
		catch (org.springframework.dao.DataIntegrityViolationException e) {
			throw new RuntimeException("No se pudo borrar el album");
		}
		*/
		
	}
	
	
	
	def getNotInAlbumButPossiblePhotos(albumId){
		
		EventAlbum album = findAlbumById(albumId);				
		
		def eventPhotos = EventPhoto.findAllByEvent(album.event);
						
		def notInAlbumPhotos = []
			
		def albumPhotos = album.getAlbumPhotos()
		log.info albumPhotos.size();
			
		eventPhotos.each {
			
			if(! albumPhotos.contains(it)){
				notInAlbumPhotos.add(it)				
			}
		}		 		
		return notInAlbumPhotos;
	}
	
	def getAlbumPhotosAsJSON(albumId){
		EventAlbum album = findAlbumById(albumId);
		return convertPhotosToJSON(album.getAlbumPhotos());
	}
	
	
	
	def getNotInAlbumButPossiblePhotosAsJSON(albumId){
		def photos = getNotInAlbumButPossiblePhotos(albumId);
		return convertPhotosToJSON(photos);
	}
	
	def convertPhotosToJSON(photos){
		Collection results = [];
		def result;
		for (EventPhoto photo : photos){
			result = [:];
			result['url'] = photo.url
			result['photoId'] = photo.id;
			result['thumbnailUrl'] = photo.thumbnailUrl;
			result['thumbnailMediumUrl'] = photo.thumbnailMediumUrl;
			results << result
		}
		return results as JSON;
	}
	
	def saveAlbum(EventAlbum album,def coverPhotoId, def selectedPhotosIds, def eventId){
		
		if (album.coverPhoto?.id != coverPhotoId){
			EventPhoto photo = EventPhoto.get(coverPhotoId);
			album.coverPhoto = photo;
		}
						
		Event event = null;
		if(album.event == null){
			event = Event.get(eventId);
			event.addToAlbums(album);
		}		
		
		
		if(album.albumPhotos!=null)
			album.albumPhotos.clear();
			
		def newAlbumPhotos= EventPhoto.getAll(selectedPhotosIds)
		
		newAlbumPhotos.each {
			album.addToAlbumPhotos(it);
			//it.addToAlbums(album);
		}
		if ( event!= null)
			event.save(flush: true);
						
		return album.save(flush: true);
	}
	
}
